#include "erniedialog.h"
#include "ui_erniedialog.h"

ErnieDialog::ErnieDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ErnieDialog)
    , m_index(0)
    , m_isStarted(false)
{
    ui->setupUi(this);
    // 设置随机数种子
    srand(QTime::currentTime().msec());

    // 加载photos目录所有文件到容器
    loadPhotos("./photos");
    qDebug() << "加载图片的个数: " << m_photos.size();

    // 定时器到时会发送timeout信号，在这里进行信号和槽的连接
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(Ontimeout()));
}

ErnieDialog::~ErnieDialog()
{
    delete ui;
}

void ErnieDialog::loadPhotos(const QString &path)
{
    // 创建目录对象
    QDir dir(path);
    // 遍历当前目录的文件
    QStringList list1 = dir.entryList(QDir::Files);
    for(int i = 0; i < list1.size(); i++)
    {
        QImage image(path + "/" + list1.at(i));
        m_photos << image;      // 将每个文件输出到m_photos容器中
    }

    // 递归遍历每个目录下的文件
    QStringList list2 = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    for(int i = 0; i < list2.size(); i++)
    {
        loadPhotos(path + "/" + list2.at(i));
    }
}

void ErnieDialog::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QRect rect = ui->frame->frameRect();
    rect.translate(ui->frame->pos());
    painter.drawImage(rect, m_photos[m_index]);
}

/*
void ErnieDialog::timerEvent(QTimerEvent *)
{
    m_index = rand() % m_photos.size();
    update();   // 触发绘图事件
}
*/

void ErnieDialog::on_pushButton_clicked()
{
    if(m_isStarted == false)
    {
        m_isStarted = true;
        // m_timer = startTimer(1000);
        m_timer.start(50);;
        ui->pushButton->setText("停止");
    }
    else
    {
        // killTimer(m_timer);
        m_timer.stop();
        m_isStarted = false;
        ui->pushButton->setText("开始");
    }
}

void ErnieDialog::Ontimeout()
{
    m_index = rand() % m_photos.size();
    update();   // 触发绘图事件
}

